package com.dhcc.DRGsHosp.facade.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Named;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openkoala.koala.commons.InvokeResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.util.StringUtils;

import com.dhcc.DRGsHosp.application.DRGVersionApplication;
import com.dhcc.DRGsHosp.application.DRGsApplication;
import com.dhcc.DRGsHosp.application.GroupFunApplication;
import com.dhcc.DRGsHosp.core.domain.DRGVersion;
import com.dhcc.DRGsHosp.core.domain.DRGs;
import com.dhcc.DRGsHosp.facade.GroupFuncFacade;
import com.dhcc.DRGsHosp.facade.GroupServiceFacade;
import com.dhcc.DRGsHosp.facade.dto.GroupFuncDTO;
import com.dhcc.DRGsHosp.infra.util.GlobalData;
import com.dhcc.DRGsHosp.infra.util.NotInGroupReasonUtil;
import org.codehaus.jackson.map.ObjectMapper;
@Named("drgsHospFacadeImpl21")
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class GroupFuncFacadeImpl implements GroupFuncFacade,Serializable{
	
	private static final long serialVersionUID = 1L;

	@Autowired
	private DRGsApplication drgsApplication;
	
	@Autowired
	private DRGVersionApplication drgsVersionApplication;
	
	
	@Autowired
	private GroupFunApplication groupFunApplication;
	
	@Autowired 
	private GroupServiceFacade groupServiceFacade;
	
	private List<Map<String, Object>> groupingResultList = new ArrayList<Map<String, Object>>();
	private String message="";//返回前台的信息
	
	private float percent;//进度完成百分比
	
	private String detail="";//进度进行详情
	

	@Override
	public InvokeResult drgsGroupPatients(GroupFuncDTO dto) {
		String groupVerCode = dto.getDrgVersion();
		DRGVersion drgVersion=drgsVersionApplication.getDRGVersion(groupVerCode);
		if (drgVersion==null) {
			return InvokeResult.failure("分组器版本错误");
		}
		String groupVer = drgVersion.getVerDesc();
		String isICDMatch=dto.getIsICDMatch();
		DRGs drgs = new DRGs();
		drgs.setVerCode(groupVerCode);
		List<DRGs> drgList = drgsApplication.findAllDRGs(drgs);
		Map<String, String> drgsMap = new HashMap<String, String>();
		List<Map<String,Object>> listDrgMap = drgsApplication.findDrgInfoByYear(groupVerCode);
		for (DRGs drg : drgList) {
			drgsMap.put(drg.getDrgCode(), drg.getDrgDesc());
		}
		ObjectMapper objectMapper = new ObjectMapper();
		
		Map<String, Object> patient = new HashMap<String, Object>();
		String groupAddr=getGroupAddr(groupVer);//获取分组器地址
		if(!StringUtils.hasLength(groupAddr)){
			return InvokeResult.failure("请配置"+groupVer+"分组器地址");
		}
		try {
			patient = objectMapper.readValue(dto.getPatient(), Map.class);
			//诊断编码版本
			String icdDiaVerConfig = drgVersion.getIcd10Version();
			//手术操作版本
			String icdOperVerConfig =drgVersion.getIcd9Version();
			//处理数据
			Map<String, Object> mrInfoMap=groupServiceFacade.dataGenerate(patient,groupVer,isICDMatch,icdDiaVerConfig,icdOperVerConfig);
			//分组器调用,是否再分组，传入false		
			Map<String,Object> resultMap=groupServiceFacade.group(mrInfoMap,groupAddr,groupVer,false);
			if(resultMap==null){
				return InvokeResult.failure("分组报错了");
			}
			String notInReasonJson=NotInGroupReasonUtil.notInGroupReason(objectMapper.writeValueAsString(mrInfoMap),objectMapper.writeValueAsString(resultMap),groupVer);
			if(groupVer!=null&&groupVer.indexOf("北京2016版")>=0){
				if(resultMap.get("log")!=null){
		    		String logs[]=resultMap.get("log").toString().split(";");
					List<String> logList=Arrays.asList(logs);
					resultMap.put("log", logList);
				}
			}
			patient.put("DRG_CODE", resultMap.get("drg"));
			patient.put("DRG_DESC", drgsMap.get(resultMap.get("drg")));
			patient.put("GROUP_LOG", resultMap.get("log"));
			/*获取病组的基本信息，平均住院日，权重，次均费用等*/
			String drgCode=resultMap.get("drg")==null?"":resultMap.get("drg").toString();
			if(drgCode!="") {
				for(Map<String,Object> map :listDrgMap) {
					String code=map.get("AS_DRG_CODE")+"";
					if(drgCode.equals(code)) {
						patient.put("DRGWEIGHT",map.get("AS_WEIGHT")==null?"":map.get("AS_WEIGHT").toString());
						patient.put("AVGDAYS",map.get("AS_AVG_DAYS")==null?"":map.get("AS_AVG_DAYS").toString() );
						patient.put("AVGFEE",map.get("AS_AVG_FEE")==null?"":map.get("AS_AVG_FEE").toString() );
						patient.put("RISKLEVEL",map.get("AS_RISK_LEVEL")==null?"":map.get("AS_RISK_LEVEL").toString() );
						break;
					}
				}
			}
			return InvokeResult.success(patient);
		} catch (Exception e) {
			e.printStackTrace();
			return InvokeResult.failure("分组报错了");
		}
	}
	
	private String getGroupAddr(String groupVer){
		//获取分组器地址
		String groupAddr ="";
		if(groupVer!=null&&groupVer.indexOf("北京2016版")>=0){
			groupAddr=GlobalData.sysConfig.get("GROUP_ADDER_2016");
		}else{
			groupAddr=GlobalData.sysConfig.get("GROUP_ADDER");
		}
		return groupAddr;
	}
	
	@Override
	public Map<String, Object> drgsGroupExcel(String filePath, String context,String groupVerCode,String isICDMatch) {
		//分组器版本
		DRGVersion drgVersion=drgsVersionApplication.getDRGVersion(groupVerCode);
		if (drgVersion==null) {
			message = "分组器版本错误";
			System.err.println(message);
			finish("已中断");
			return null;
		}
		//诊断编码版本
		String icdDiaVerConfig = drgVersion.getIcd10Version();
		//手术操作版本
		String icdOperVerConfig =drgVersion.getIcd9Version();
		String groupVer=drgVersion.getVerDesc();//获取DRGs版本号
		String groupAddr=getGroupAddr(groupVer);//获取分组器地址
		if(!StringUtils.hasLength(groupAddr)){
			message = "请配置"+groupVer+"分组器地址";
			System.err.println("请配置"+groupVer+"分组器地址");
			finish("已中断");
	    	return null;
		}
		DRGs drgsDTO = new DRGs();
		drgsDTO.setVerCode(groupVerCode);
		List<DRGs> drgList = drgsApplication.findAllDRGs(drgsDTO);
		/*获取病组权重*/
		List<Map<String,Object>> listDrgMap = drgsApplication.findDrgInfoByYear(groupVerCode);
		Map<String, String> drgsMap = new HashMap<String, String>();
		for (DRGs drgs : drgList) {
			drgsMap.put(drgs.getDrgCode(), drgs.getDrgDesc());
		}
		
		String extension=filePath.substring(filePath.lastIndexOf("."));//扩展名
		List<Map<String, Object>> resultList = new ArrayList<Map<String,Object>>();
		message="";
		percent=0;
		detail="";
		int grouped = 0;
		int ungrouped = 0;
		int days60 = 0;
		
		if(".xls".equals(extension) || ".xlsx".equals(extension)){
			int errorRow = 0;
			int errorCell=0;
			
			try {
				Workbook workbook=null;
				Sheet sheet=null;
				Row row=null;
				Row firstrow=null;
				Cell cell=null;
				if (extension.equals(".xls")) {
					try {
						workbook=new HSSFWorkbook(new FileInputStream(filePath));
						sheet=(HSSFSheet) workbook.getSheetAt(0);
	
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else if(extension.equals(".xlsx")){
					try {
						workbook=new XSSFWorkbook(new FileInputStream(filePath));
						sheet=(XSSFSheet)workbook.getSheetAt(0);
	
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
				message = "解析Excel...";
				//读取表头数据
				firstrow = sheet.getRow(0);
				int colNum = firstrow.getPhysicalNumberOfCells();  
				String[] title = new String[colNum];
				
				//读取表头数据
				System.out.println("表头大小为："+firstrow.getLastCellNum());
				for (int i = 0; i < firstrow.getLastCellNum(); i++) {
					cell = firstrow.getCell((short) i);
					title[i] = cell.getStringCellValue();
					//暂停50毫秒
			    	try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					detail = title[i];
					System.out.println("==========下面是title==============="+title[i]);
				}
				
				//读取表单数据，读取表单行的数据
				detail = "读取表单行的数据";
				int rowTemp =sheet.getLastRowNum();
				for (int numRows = 1; numRows <= rowTemp; numRows++) {
					errorRow = numRows;
					row = sheet.getRow(numRows);
					
					//打印进度
					printProgress(rowTemp, numRows);
					
					String diaICD=null;//诊断编码，每行数据定义一个诊断编码，用来存储不同诊断的编码。
					String operICD=null;//诊断编码，每行数据定义一个诊断编码，用来存储不同诊断的编码。
					
					Map<String, Object> patient = new HashMap<String, Object>();
					patient.put("ver", groupVer);
					List<String> diags = new ArrayList<>();
					List<String> opers = new ArrayList<>();
					//读取表单每行数据的每列数据，即每行数据的每个cell格
					for (int numCells = 0; numCells < row.getLastCellNum(); numCells++) {
						cell = row.getCell((short) numCells);
						String colTitle =null;
						colTitle = title[numCells];
						errorCell = numCells;
						
						//处理字段名称问题
						colTitle=colTitle.replaceAll("^主要诊断(名称)?$", "主要诊断");
						colTitle=colTitle.replaceAll("^主要手术(名称)?$", "主要手术");
						
						colTitle=colTitle.replaceAll("^其[他它]诊断\\d{1,2}ICD$", "其它诊断ICD");
						colTitle=colTitle.replaceAll("^其[他它]诊断\\d{1,2}(名称)?$", "其它诊断");
						
						colTitle=colTitle.replaceAll("^其[他它]手术\\d{1,2}ICD$", "其它手术ICD");
						colTitle=colTitle.replaceAll("^其[他它]手术\\d{1,2}(名称)?$", "其它手术");
						
						colTitle=colTitle.replaceAll("^操作\\d{1,2}ICD$", "其它手术ICD");
						colTitle=colTitle.replaceAll("^操作\\d{1,2}(名称)?$", "其它手术");
						
					  //根据title的取值进行对比
					  switch (colTitle) {
						case "病案号":
							if(cell!=null){
								if(cell.getCellType() == Cell.CELL_TYPE_STRING)
								{//字符串类型
									patient.put("CASE_ID", cell.getStringCellValue());
								}
								else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
								{//数字类型
									patient.put("CASE_ID", cell.getNumericCellValue());
								}
							}
							break;
						case "性别":
							if(cell!=null){
							  row.getCell(numCells).setCellType(Cell.CELL_TYPE_STRING); 
							  String sex=cell.getStringCellValue();
							  patient.put("GENDER", sex);
							}
							break;
						case "年龄":
							if(cell!=null){
								 if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
						              patient.put("AGE", Double.valueOf(cell.getStringCellValue()));
						         } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
									  patient.put("AGE", (double) cell.getNumericCellValue());
						         }
							}
							break;
						case "总费用":
							if(cell!=null){
								if(cell.getCellType() == Cell.CELL_TYPE_STRING)
								{//字符串类型
									patient.put("TOTAL_EXPENSE", cell.getStringCellValue());
								}
								else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
								{//数字类型
									patient.put("TOTAL_EXPENSE", cell.getNumericCellValue());
								}
							}
							break;
						case "离院方式":
							if(cell!=null){
								if(cell.getCellType() == Cell.CELL_TYPE_STRING)
								{//字符串类型
									patient.put("SF0108", cell.getStringCellValue());
								}
								else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
								{//数字类型
									patient.put("SF0108", cell.getNumericCellValue());
								}
							}
							break;
						case "出院方式":
							if(cell!=null){
								if(cell.getCellType() == Cell.CELL_TYPE_STRING)
								{//字符串类型
									patient.put("SF0108", cell.getStringCellValue());
								}
								else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
								{//数字类型
									patient.put("SF0108", cell.getNumericCellValue());
								}
							}
							break;
						case "主要诊断ICD":
							diaICD=null;
							if(cell!=null){
								if (!"".equals(cell.getStringCellValue())) {
									diaICD=cell.getStringCellValue();
									patient.put("DISEASE_CODE",diaICD);//主要诊断
								}
							}
							break;
						case "其它诊断ICD":
							diaICD=null;
							if(cell!=null){
								if(cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
								{
									diaICD=cell.getStringCellValue();
									diags.add(diaICD);
								}
								else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
								{
									diaICD=String.valueOf(cell.getNumericCellValue());
									diags.add(diaICD);
								}
							}
							break;
						case "主要手术ICD":
							operICD=null;
							if(cell!=null){
								if(cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
								{
									operICD=cell.getStringCellValue();
									opers.add(operICD);
								}
								else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
								{
									operICD=String.valueOf(cell.getNumericCellValue());
									opers.add(operICD);
								}
							}
							break;
						case "其它手术ICD":
							operICD=null;
							if(cell!=null){
								if(cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
								{
									operICD=cell.getStringCellValue();
									opers.add(operICD);
								}
								else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
								{
									operICD=String.valueOf(cell.getNumericCellValue());
									opers.add(operICD);
								}
							}
							break;
						case "新生儿年龄":
							if(cell!=null){
								if(cell.getCellType() == Cell.CELL_TYPE_STRING)
								{//字符串类型
									patient.put("SF0100", cell.getStringCellValue());
								}
								else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
								{//数字类型
									patient.put("SF0100", cell.getNumericCellValue());
								}
							}
							break;		
						case "新生儿入院体重":
							if(cell!=null){
								if(cell.getCellType() == Cell.CELL_TYPE_STRING)
								{//字符串类型
									patient.put("SF0102", cell.getStringCellValue());
								}
								else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
								{//数字类型
									patient.put("SF0102", cell.getNumericCellValue());
								}
							}
							break;
						case "呼吸机使用时间":
							if(cell!=null){
								if(cell.getCellType() == Cell.CELL_TYPE_STRING)
								{//字符串类型
									patient.put("SF0104", cell.getStringCellValue());
								}
								else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
								{//数字类型
									patient.put("SF0104", cell.getNumericCellValue());
								}
							}
							break;
						case "住院天数":
							if(cell!=null){
								if(cell.getCellType() == Cell.CELL_TYPE_STRING)
								{//字符串类型
									patient.put("ACCTUAL_DAYS", cell.getStringCellValue());
								}
								else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
								{//数字类型
									patient.put("ACCTUAL_DAYS", cell.getNumericCellValue());
								}
							}
							break;
					}
					if (diags.size()>0) {
						patient.put("DIAGS_CODE", diags);
					}
					if (opers.size()>0) {
						patient.put("OPERS_CODE", opers);
					}
				}
				if (Double.valueOf(patient.get("ACCTUAL_DAYS")+"")>60) {
					resultList.add(patient);
					days60++;
					continue;
				}
				message = "进行分组...";
				//分组器调用					
				Map<String, Object> resultMap=new HashMap<>();
				try {
					//处理数据
					Map<String, Object> mrInfoMap=groupServiceFacade.dataGenerate(patient,groupVer,isICDMatch,icdDiaVerConfig,icdOperVerConfig);
					//是否再分组，传入false
					resultMap=groupServiceFacade.group(mrInfoMap,groupAddr,groupVer,false);
					if(groupVer!=null&&groupVer.indexOf("北京2016版")>=0){
						String logs[]=resultMap.get("log").toString().split(";");
						List<String> logList=Arrays.asList(logs);
						resultMap.put("log", logList);
					}
					
				} catch (Exception e) {
					e.printStackTrace();
					message = "分组报错了...";
					System.err.println("分组报错了");
					finish("已中断");
			    	return null;
				}
				/*获取病组的基本信息，平均住院日，权重，次均费用等*/
				String drgCode=resultMap.get("drg")==null?"":resultMap.get("drg").toString();
				if(drgCode!="") {
					for(Map<String,Object> map :listDrgMap) {
						String code=map.get("AS_DRG_CODE")+"";
						if(drgCode.equals(code)) {
							patient.put("DRGWEIGHT",map.get("AS_WEIGHT")==null?"":map.get("AS_WEIGHT").toString());
							patient.put("AVGDAYS",map.get("AS_AVG_DAYS")==null?"":map.get("AS_AVG_DAYS").toString() );
							patient.put("AVGFEE",map.get("AS_AVG_FEE")==null?"":map.get("AS_AVG_FEE").toString() );
							patient.put("RISKLEVEL",map.get("AS_RISK_LEVEL")==null?"":map.get("AS_RISK_LEVEL").toString() );
							break;
						}
					}
				}
				patient.put("DRG_CODE", resultMap.get("drg"));
				patient.put("DRG_DESC", drgsMap.get(resultMap.get("drg")));
				patient.put("GROUP_LOG", resultMap.get("log"));
				
				resultList.add(patient);
				
//				String drgCode = resultMap.get("drg")+"";
				detail = patient.get("CASE_ID")+":"+drgCode;
				if (drgCode.matches("^\\w{1,2}QY$")) {
					//如果drgCode为QY结尾则存为未分组
					ungrouped++;
				} else if (drgCode.matches("^\\d{4}$")) {
					ungrouped++;
				}else {
					grouped++;
				}
			}
			
			//删除upload文件夹下的所有文件
			File tempFile = new File(filePath);
			if(tempFile.isFile() || tempFile.list().length ==0)  {  
				System.out.println("============删除tempFile1=============");
				tempFile.delete();       
			}else{      
				File[] tempFiles = tempFile.listFiles();  
				for (int i = 0; i < tempFiles.length; i++) {  
					System.out.println("============删除tempFile2=============");
					tempFiles[i].delete();      
				}
			}
			StringBuilder s=new StringBuilder();
			s.append("<table><tr><td>总病例数:"+resultList.size()+"</td><td>已分组:"+grouped+"</td><td>未入组:"+ungrouped+"</td>");
			s.append("<td>大于60天病例:"+days60+"</td><td>入组率:"+(grouped*100/(resultList.size()-days60))+"%</td></tr></table>");
			message = s.toString();
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("message", s.toString());
			map.put("data", resultList);
			
			finish("已完成");
			return map;
			
		} 
		catch (Exception e) {
			e.printStackTrace();
			int a =errorRow+1;
			errorCell=errorCell+1;
			message = "首页数据Excel的第"+a+"行第"+errorCell+"列数据有问题，请检查后重新提交";
			System.err.println(message);
			finish("已中断");
	    	return null;
		}
	}
	else {
		message = "上传的文件格式有误，请检查后重新上传";
		System.err.println(message);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("hasErrors",true);
		finish("已中断");
		return null;
	}
}
	/**
	 * @methodname    :finish
	 * @description   :完成状态
	 * @param         :s:已完成 or 已中断
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年7月3日
	 */
	private void finish(String s) {
		//暂停2500毫秒
    	try {
			Thread.sleep(2500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    	message=s;
    	//暂停2500毫秒
    	try {
			Thread.sleep(2500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    	percent=0;
    	detail="";
    	message="";
	}

	
	/**
	 * 
	 *  @Description：根据病案号从数据库中查询病例信息
	 *  @Author ZouYiyu  
	 *  @see com.dhcc.DRGsHosp.facade.GroupFuncFacade#findPatientInDatabase(java.lang.String)
	 */
	@Override
	public List<Map<String,Object>> findPatientInDatabase(String mrNo){
		String configGroupVer = GlobalData.sysConfig.get("GROUP_VER");
		String verRegion=drgsVersionApplication.getDrgRegionByVerCode(configGroupVer);
		List<Map<String, Object>> resultList=groupFunApplication.findPatientInDatabase(mrNo,verRegion);
    	return resultList;
    }
	@Override
	public String replaceGroupResult (String doInsert){
		if("yes".equals(doInsert)){
			for(int i=0;i<groupingResultList.size();i++){
				Map<String,Object> mapR=groupingResultList.get(i);
				groupServiceFacade.groupResultLogSave((Map<String,Object>)mapR.get("GROUP_INFO"),(Map<String,Object>)mapR.get("GROUP_RESULT"),mapR.get("GROUP_VER_CODE").toString(),mapR.get("GROUP_VER_DESC").toString(),mapR.get("VER_REGION").toString(),mapR.get("ICD_MATCH").toString());
			}
			return "1";
		}
			
		return "更新失败";
	}
	
	@Override
	public InvokeResult findAndGroupPatient(String mrNo,String groupVerCode,String isICDMatch){
		DRGVersion drgVersion=drgsVersionApplication.getDRGVersion(groupVerCode);
		if(drgVersion==null){
			return InvokeResult.failure("分组器版本错误");
		}
		String groupVer = drgVersion.getVerDesc();
		//获取分组器地址
		String groupAddr=getGroupAddr(groupVer);
		if(!StringUtils.hasLength(groupAddr)){
			return InvokeResult.failure("请配置"+groupVer+"分组器地址");
		}
		//诊断编码版本
		String icdDiaVerConfig = drgVersion.getIcd10Version();
		//手术操作版本
		String icdOperVerConfig =drgVersion.getIcd9Version();
		//获取系统配置中的分组器方案--查询病例数据时，需要查系统的分组结果，需要带这一参数,注意与加到分组结果的map中的verregion意义不一样，分组结果中map放的时在线分组所选择的分组器版本对应的分组方案
		String configGroupVer = GlobalData.sysConfig.get("GROUP_VER");
		String verRegion=drgsVersionApplication.getDrgRegionByVerCode(configGroupVer);
		List<Map<String,Object>> listDrgMap = drgsApplication.findDrgInfoByYear(groupVerCode);
		//查询DRG字典
		DRGs drgs = new DRGs();
		drgs.setVerCode(groupVerCode);
		List<DRGs> drgList = drgsApplication.findAllDRGs(drgs);
		Map<String, String> drgsMap = new HashMap<String, String>();
		for (DRGs drg : drgList) {
			drgsMap.put(drg.getDrgCode(), drg.getDrgDesc());
		}
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> list=groupFunApplication.findPatientByMrNo(mrNo, verRegion);
		if(list.size()>0){
    		for(Map<String, Object> map:list){
				//获取其他诊断信息
    			String diags = map.get("DIAGS")!=null?map.get("DIAGS").toString():null;
				if(StringUtils.hasLength(diags)){
					map.put("DIAGS_CODE", Arrays.asList(diags.split(",")));
				}
				String opers = map.get("OPERS")!=null?map.get("OPERS").toString():null;
				if(StringUtils.hasLength(opers)){
					map.put("OPERS_CODE", Arrays.asList(opers.split(",")));
				}
				//分组器调用					
				Map<String, Object> resultMap=new HashMap<>();
				Map<String, Object> mrInfoMap=new HashMap<>();
				try {
					//处理数据
					mrInfoMap=groupServiceFacade.dataGenerate(map,groupVer,isICDMatch,icdDiaVerConfig,icdOperVerConfig);
					resultMap=groupServiceFacade.group(mrInfoMap,groupAddr,groupVer,false);
					if(resultMap==null){
						return InvokeResult.failure("分组报错了");
					}
				} catch (Exception e) {
					e.printStackTrace();
					return InvokeResult.failure("分组报错了");
				}
				if(groupVer!=null&&groupVer.indexOf("北京2016版")>=0){
					String logs[]=resultMap.get("log").toString().split(";");
					List<String> logList=Arrays.asList(logs);
					resultMap.put("log", logList);
				}
				@SuppressWarnings("unchecked")
				List<String> logList=(List<String>)resultMap.get("log");
				map.put("New_DRG_CODE", resultMap.get("drg"));
				map.put("New_DRG_DESC", drgsMap.get(resultMap.get("drg")));
				map.put("GROUP_LOG", logList);
				map.put("Old_Drgs_Code", map.get("DRG_CODE"));
				map.put("Old_Drgs_Desc", map.get("DRG_DESC"));
				map.put("GROUP_VER_CODE", groupVerCode);
				map.put("GROUP_VER_DESC", groupVer);
				map.put("VER_REGION",drgVersion.getRegionCode());//替换系统内分组结果时用，这里用页面中选择的分组器版本的regioncode
				map.put("PARID", map.get("CASE_ID"));
				map.put("GROUP_RESULT", resultMap);//新增by wen
				map.put("GROUP_INFO", mrInfoMap);//新增by wen
				map.put("ICD_MATCH", isICDMatch);//新增by wen
				/*获取病组的基本信息，平均住院日，权重，次均费用等*/
				String drgCode=map.get("New_DRG_CODE")==null?"":map.get("New_DRG_CODE").toString();
				if(drgCode!="") {
					for(Map<String,Object> mapo :listDrgMap) {
						String code=mapo.get("AS_DRG_CODE")+"";
						if(drgCode.equals(code)) {
							map.put("DRGWEIGHT",mapo.get("AS_WEIGHT")==null?"":mapo.get("AS_WEIGHT").toString());
							map.put("AVGDAYS",mapo.get("AS_AVG_DAYS")==null?"":mapo.get("AS_AVG_DAYS").toString() );
							map.put("AVGFEE",mapo.get("AS_AVG_FEE")==null?"":mapo.get("AS_AVG_FEE").toString() );
							map.put("RISKLEVEL",mapo.get("AS_RISK_LEVEL")==null?"":mapo.get("AS_RISK_LEVEL").toString() );
							break;
						}
					}
				}
				resultList.add(map);
    		}
		}
		groupingResultList=resultList;//将分组结果存入一个listmap中，用于覆盖原有分组结果
    	return InvokeResult.success(resultList);
    	
	}
	
	/**
	 * @methodname    :getProgress
	 * @description   :获取执行进度
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年1月27日
	 */
	public void getProgress(HttpServletResponse response){
		DecimalFormat df = new DecimalFormat("##0.00");
		response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer=null;
        do {
        	//循环输出进度信息
	    	try {
	    		writer=response.getWriter();
	    		writer.write("data: {\"msg\":\""+message+"\",\"percent\":\""+df.format(percent)+"\",\"detail\":\""+detail+"\"}\n\n");
				writer.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
	    	
	    	if (percent==100) {
	            break;//进度为100是退出循环
			}
	    	
	    	//暂停20毫秒
	    	try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        } while (percent<=100);//进度为100是退出循环
        
        writer.close();
		System.out.println("进度信息调用完毕");
	}
	
	/**
	 * @methodname    :printProgress
	 * @description   :打印循环的进度
	 * @param         :total：总数，i：当前位置
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年1月26日
	 */
	private void printProgress(int total,int i) {
		percent=(float)i*100/(float)total;
	}
}
